package cn.rongdao.jrkabao.ui.cashadvance.addcard;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.mifengkong.frtools.http.request.callback.FRBaseObserver;
import com.mifengkong.frtools.inputmethod.FRInputMethodManager;
import com.mifengkong.frtools.ui.activity.FRStartActivity;
import com.mifengkong.frtools.util.FRCollection;
import com.mifengkong.frtools.util.FRString;
import com.mifengkong.frwidget.sidebar.SideBar;
import com.mifengkong.frwidget.titlebar.TitleBarUIComponent;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import cn.rongdao.jrkabao.R;
import cn.rongdao.jrkabao.base.BaseAutoFinishActivity;
import cn.rongdao.jrkabao.bean.cashadvance.SelectBankCardBean;
import cn.rongdao.jrkabao.model.cashadvance.SelectBankCardModel;
import cn.rongdao.jrkabao.ui.cashadvance.adapter.SelectBankCardAdapter;
import cn.rongdao.jrkabao.ui.cashadvance.adapter.StickyHeaderDecoration;
import cn.rongdao.jrkabao.util.CommonUtil;
import cn.rongdao.jrkabao.util.SelectBankUtil;
import cn.rongdao.jrkabao.util.SortByPinyin;
import cn.rongdao.jrkabao.util.listener.OnTextChangeListener;

/**
 * Created by jack on 2017/8/8
 */

public class SelectBankCardActivity extends BaseAutoFinishActivity {

    public static final int SELECT_BANK_CODE_RESULT_CODE = 0x1111;

    public static final String BANK_NAME = "bank_name";

    public static final String BANK_ICON = "bank_icon";

    public static final String BANK_CODE = "bank_code";

    public static final String BANK_TYPE = "type";

    public static void start(Activity context, boolean type, int resultCode) {
        Bundle bundle = new Bundle();
        bundle.putBoolean(BANK_TYPE, type);
        FRStartActivity.startForResult(context, SelectBankCardActivity.class, bundle, resultCode);
    }

    @BindView(R.id.asbc_titlebar)
    TitleBarUIComponent titleBarUIComponent;
    @BindView(R.id.asbc_iv_delete)
    ImageView ivClear;
    @BindView(R.id.asbc_tv_search_result)
    TextView tvSearchResult;
    @BindView(R.id.asbc_et_search)
    EditText etSearch;
    @BindView(R.id.asbc_recyclerview)
    RecyclerView recyclerView;
    @BindView(R.id.asbc_sidebar)
    SideBar sideBar;
    @BindView(R.id.asbc_tv_no_find)
    TextView tvNoFind;

    ArrayList<SelectBankCardBean> mList = new ArrayList<>();
    ArrayList<SelectBankCardBean> searchList = new ArrayList<>();//用于搜索的集合数据
    private SelectBankCardAdapter mAdapter;
    private LinearLayoutManager manager;

    private boolean isCreditCard;

    @Override
    protected int layoutRes() {
        return R.layout.activity_select_bank_card;
    }

    @Override
    protected void initView() {
        super.initView();
        initTitleBar();
        isCreditCard = getIntent().getBooleanExtra(BANK_TYPE, false);
        mAdapter = new SelectBankCardAdapter(this, mList);
        manager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(manager);
        recyclerView.setHasFixedSize(true);
        //设置悬浮索引
        StickyHeaderDecoration decoration = new StickyHeaderDecoration(mAdapter);
        recyclerView.setAdapter(mAdapter);
        recyclerView.addItemDecoration(decoration);
        initListener();
        initData();
    }

    private void initData() {
        SelectBankCardModel.getInstance().execute(isCreditCard, new FRBaseObserver<List<SelectBankCardBean>>(this, "加载中，请稍候...") {
            @Override
            protected void onBaseNext(List<SelectBankCardBean> data) {
                formatData(data);
            }
        });
    }

    //数据排序A~Z
    private void formatData(List<SelectBankCardBean> data) {
        SelectBankCardBean selectBankCardBean;
        for (int i = 0; i < data.size(); i++) {
            selectBankCardBean = data.get(i);
            if (!TextUtils.isEmpty(selectBankCardBean.getBank_name())) {
                SelectBankUtil.getPinyinList(selectBankCardBean);
            } else {
                selectBankCardBean.setPinyinFirst("#");
            }
            searchList.add(selectBankCardBean);
        }
        Collections.sort(searchList, new SortByPinyin());
        mList.addAll(searchList);
        mAdapter.notifyDataSetChanged();
    }

    private void initListener() {
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                FRInputMethodManager.hideSoftInput(thisActivity());
                for (int i = 0; i < mList.size(); i++) {
                    int position = mAdapter.getPositionForSection(mList.get(i).getPinyinFirst().charAt(0));
                    if (s.equals("☆")) {
                        manager.scrollToPositionWithOffset(position, 0);
                        break;
                    }
                    if (s.equals(FRString.valueOf(mList.get(i).getPinyinFirst()))) {
                        if (position != -1) {
                            //滑动到指定位置
                            manager.scrollToPositionWithOffset(position, 0);
                        }
                        break;
                    }
                }
            }
        });

        etSearch.addTextChangedListener(new OnTextChangeListener() {
            @Override
            public void afterTextChanged(Editable s) {
                filtDatas(s.toString());
            }
        });

        ivClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etSearch.setText("");
            }
        });

        mAdapter.setOnSelectBankCardClickListener(new SelectBankCardAdapter.OnSelectBankCardClickListener() {
            @Override
            public void click(View v, int position) {
                Intent intent = new Intent();
                intent.putExtra(BANK_NAME, mList.get(position).getBank_name());
                intent.putExtra(BANK_ICON, mList.get(position).getBank_icon());
                intent.putExtra(BANK_CODE, mList.get(position).getBank_code());
                setResult(SELECT_BANK_CODE_RESULT_CODE, intent);
                finish();
            }
        });
    }

    private void filtDatas(String s) {
        if (searchList.size() == 0) {
            return;
        }
        resetSearchData();
        if (FRString.isEmpty(s)) {
            setContentVisible(false);
            tvSearchResult.setVisibility(View.GONE);
            mList.clear();
            mList.addAll(searchList);
            mAdapter.notifyDataSetChanged();
            ivClear.setVisibility(View.GONE);
            return;
        }
        ivClear.setVisibility(View.VISIBLE);
        mList.clear();
        if (CommonUtil.isContainChinese(s)) {
            findDataByNumberOrCN(s);
        } else if (CommonUtil.isEnglishAlphabet(s)) {
            findDataByEN(s);
        } else {
            findDataByNumberOrCN(s);
        }
        if (mList.size() <= 0) {
            setContentVisible(true);
        } else {
            setContentVisible(false);
            tvSearchResult.setText(FRCollection.appendAsString("找到", FRString.valueOf(mList.size()), "个结果", ""));
            mAdapter.notifyDataSetChanged();
        }
    }

    private void setContentVisible(boolean isVisible) {
        tvNoFind.setVisibility(isVisible ? View.VISIBLE : View.GONE);
        tvSearchResult.setVisibility(!isVisible ? View.VISIBLE : View.GONE);
        recyclerView.setVisibility(!isVisible ? View.VISIBLE : View.GONE);
        sideBar.setVisibility(!isVisible ? View.VISIBLE : View.GONE);
    }

    private void resetSearchData() {
        for (int i = 0; i < searchList.size(); i++) {
            searchList.get(i).setHighLight(false);//重置为不高亮
        }
    }

    private void findDataByEN(String inputStr) {
        //把输入的内容变为大写
        String searPinyin = CommonUtil.transformPinYin(inputStr);
        //搜索字符串的长度
        int searLength = searPinyin.length();
        //搜索的第一个大写字母
        for (int i = 0; i < searchList.size(); i++) {
            SelectBankCardBean contactsBean = searchList.get(i);
            //如果输入的每一个字母都和名字的首字母一样，那就可以匹配比如：你好，NH，输入nh就ok
            if (contactsBean.getMatchPin().contains(searPinyin)) {
                contactsBean.setHighLight(true);
                contactsBean.setHighlightedStart(contactsBean.getMatchPin().indexOf(searPinyin));
                contactsBean.setHighlightedEnd(contactsBean.getHighlightedStart() + searLength);
                mList.add(contactsBean);
            } else {
                boolean isMatch = false;
                //先去匹配单个字，比如你好：NI,HAO.输入NI，肯定匹配第一个
                for (int j = 0; j < contactsBean.getNamePinyinList().size(); j++) {
                    String namePinyinPer = contactsBean.getNamePinyinList().get(j);
                    if (!TextUtils.isEmpty(namePinyinPer) && namePinyinPer.startsWith(searPinyin)) {
                        //符合的话就是当前字匹配成功
                        contactsBean.setHighLight(true);
                        contactsBean.setHighlightedStart(j);
                        contactsBean.setHighlightedEnd(j + 1);
                        mList.add(contactsBean);
                        isMatch = true;
                        break;
                    }
                }
                if (isMatch) {
                    continue;
                }
                //根据拼音包含来实现，比如你好：NIHAO,输入NIHA或者NIHAO。
                if (!TextUtils.isEmpty(contactsBean.getNamePinYin()) && contactsBean.getNamePinYin().contains(searPinyin)) {
                    //这样的话就要从每个字的拼音开始匹配起
                    for (int j = 0; j < contactsBean.getNamePinyinList().size(); j++) {
                        StringBuilder sbMatch = new StringBuilder();
                        for (int k = j; k < contactsBean.getNamePinyinList().size(); k++) {
                            sbMatch.append(contactsBean.getNamePinyinList().get(k));
                        }
                        if (sbMatch.toString().startsWith(searPinyin)) {
                            //匹配成功
                            contactsBean.setHighlightedStart(j);
                            int length = 0;
                            //比如输入是NIH，或者NIHA,或者NIHAO,这些都可以匹配上，从而就可以通过NIHAO>=NIH,HIHA,NIHAO
                            for (int k = j; k < contactsBean.getNamePinyinList().size(); k++) {
                                length = length + contactsBean.getNamePinyinList().get(k).length();
                                if (length >= searLength) {
                                    contactsBean.setHighlightedEnd(k + 1);
                                    break;
                                }
                            }
                            contactsBean.setHighLight(true);
                            isMatch = true;
                            mList.add(contactsBean);
                        }
                    }
                }

                if (isMatch) {
                    continue;
                }

                //最后一种情况比如：广发银行，输入GuangFY或者GuangFYH都可以匹配成功，这样的情况名字集合必须大于等于3
                if (contactsBean.getNamePinyinList().size() > 2) {
                    for (int j = 0; j < contactsBean.getNamePinyinList().size(); j++) {

                        StringBuilder sbMatch0 = new StringBuilder();
                        sbMatch0.append(contactsBean.getNamePinyinList().get(j));
                        //只匹配到倒数第二个
                        if (j < contactsBean.getNamePinyinList().size() - 2) {
                            for (int k = j + 1; k < contactsBean.getMatchPin().length(); k++) {
                                //依次添加后面每个字的首字母
                                sbMatch0.append(contactsBean.getMatchPin().charAt(k));
                                if (sbMatch0.toString().equals(searPinyin)) {
                                    contactsBean.setHighLight(true);
                                    contactsBean.setHighlightedStart(j);
                                    contactsBean.setHighlightedEnd(k + 1);
                                    mList.add(contactsBean);
                                    isMatch = true;
                                    break;
                                }
                            }
                        }

                        if (isMatch) {
                            //跳出循环已找到
                            break;
                        }

                        //sbMatch1是循环匹配对象比如GUANGFYH，GUANGFAYH，GUANGFAYINH,GUANGFAYINHANG，
                        //FAYH,YINH
                        StringBuilder sbMatch1 = new StringBuilder();
                        for (int k = 0; k <= j; k++) {//依次作为初始匹配的起点
                            sbMatch1.append(contactsBean.getNamePinyinList().get(k));
                        }
                        //只匹配到倒数第二个
                        if (j < contactsBean.getNamePinyinList().size() - 2) {
                            for (int k = j + 1; k < contactsBean.getMatchPin().length(); k++) {
                                //依次添加后面每个字的首字母
                                sbMatch1.append(contactsBean.getMatchPin().charAt(k));
                                if (sbMatch1.toString().equals(searPinyin)) {
                                    contactsBean.setHighLight(true);
                                    contactsBean.setHighlightedStart(j);
                                    contactsBean.setHighlightedEnd(k + 1);
                                    mList.add(contactsBean);
                                    isMatch = true;
                                    break;
                                }
                            }
                        }
                        if (isMatch) {
                            //跳出循环已找到
                            break;
                        }

                        if (j >= contactsBean.getNamePinyinList().size() - 2) {
                            //如果说是剩余最后两个拼音不需要匹配了
                            break;
                        }
                        StringBuilder sbMatch2 = new StringBuilder();
                        sbMatch2.append(contactsBean.getNamePinyinList().get(j));
                        for (int k = j + 1; k < contactsBean.getNamePinyinList().size(); k++) {
                            sbMatch2.append(contactsBean.getNamePinyinList().get(k));
                            StringBuilder sbMatch3 = new StringBuilder();
                            sbMatch3.append(sbMatch2.toString());
                            //只匹配到倒数第二个
                            if (j < contactsBean.getNamePinyinList().size() - 2) {
                                for (int m = k + 1; m < contactsBean.getMatchPin().length(); m++) {
                                    //依次添加后面每个字的首字母
                                    sbMatch3.append(contactsBean.getMatchPin().charAt(m));
                                    if (sbMatch3.toString().equals(searPinyin)) {
                                        contactsBean.setHighLight(true);
                                        contactsBean.setHighlightedStart(j);
                                        contactsBean.setHighlightedEnd(m + 1);
                                        mList.add(contactsBean);
                                        isMatch = true;
                                        break;
                                    }
                                }
                            }
                            if (isMatch) {
                                //跳出循环已找到
                                break;
                            }
                        }
                        if (isMatch) {
                            //跳出循环已找到
                            break;
                        }
                    }
                }
            }
        }
    }

    private void findDataByNumberOrCN(String s) {
        for (int i = 0; i < searchList.size(); i++) {
            SelectBankCardBean contactsBean = searchList.get(i);
            if (!TextUtils.isEmpty(contactsBean.getBank_name()) && contactsBean.getBank_name().contains(s)) {
                contactsBean.setHighLight(true);
                contactsBean.setHighlightedStart(contactsBean.getBank_name().indexOf(s));
                contactsBean.setHighlightedEnd(contactsBean.getHighlightedStart() + s.length());
                mList.add(contactsBean);
            }
        }
    }

    private void initTitleBar() {
        titleBarUIComponent.setBackgroundColor(Color.WHITE);
        titleBarUIComponent.initLeftBackBlack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        titleBarUIComponent.initTitleBlack("选择银行");
    }
}